package com.joshluisaac.restful;

import static spark.Spark.*;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import spark.Request;
import spark.Response;
import spark.Route;

//import spark.examples.books.Book;

/**
 * A simple RESTful example showing howto create, get, update and delete book
 * resources.
 */
public class Books2 {

	private static final Logger logger = LoggerFactory.getLogger(Books.class);

	/**
	 * Map holding the books
	 */
	private static Map<String, Book> books = new HashMap<String, Book>();

	static File file;
	static int maxFileSize = 5000 * 1024;
	static int maxMemSize = 5000 * 1024;

	public static void main(String[] args) {

		externalStaticFileLocation("/media/allihave/springsrcworkspace/sparklearning/src/main/public");
		// setPort(9090);

		// Creates a new book resource, will return the ID to the created
		// resource
		// author and title are sent as query parameters e.g.
		// /books?author=Foo&title=Bar
		post(new Route("/books") {
			Random random = new Random();

			@Override
			public Object handle(Request request, Response response) {
				String author = request.queryParams("author");
				String title = request.queryParams("title");
				String filename = request.queryParams("filename");
				Book book = new Book(author, title);

				int id = random.nextInt(Integer.MAX_VALUE);
				books.put(String.valueOf(id), book);
				books.put("100", new Book("John Lennox",
						"God, the universe and Stephen Hawkins"));
				books.put("101", new Book("C S Lewis", "Screw tape letters"));
				books.put("102", new Book("Sir. Isaac Newton",
						"Principe Mathematica"));
				books.put("103", new Book("Author 103", "Book 103"));
				books.put("104", new Book("Author 104", "Author 104"));
				logger.info("{}", id);

				request.contentLength();
				String contentType = request.contentType();
				Set<String> headerSet = request.headers();
				Iterator<String> headerIterator = headerSet.iterator();
				String items = "";
				while (headerIterator.hasNext()) {
					String headerItem = headerIterator.next();
					String headerValue = request.headers(headerItem);
					items += headerItem + ": " + headerValue + "\n";
				}


				String message = "";
				if ((contentType.indexOf("multipart/form-data") >= 0)) {

					message = "Form data contains multipart/form-data";

				} else {
					message = "Form data does not contain multipart/form-data";
				}

				response.status(201); // 201 Created

				return title + "\n" + items + "\n" + filename + "\n"
						+ contentType + "\n" + message + "\n";
				// + requestBody;
			}
		});

		// Gets the book resource for the provided id
		get(new Route("/books/:id") {
			@Override
			public Object handle(Request request, Response response) {
				Book book = books.get(request.params(":id"));
				if (book != null) {
					return "Title: " + book.getTitle() + ", Author: "
							+ book.getAuthor();
				} else {
					response.status(404); // 404 Not found
					return "Book not found" + request.params("id");
				}
			}
		});

		// Updates the book resource for the provided id with new information
		// author and title are sent as query parameters e.g.
		// /books/<id>?author=Foo&title=Bar
		put(new Route("/books/:id") {
			@Override
			public Object handle(Request request, Response response) {
				String id = request.params(":id");
				Book book = books.get(id);
				if (book != null) {
					String newAuthor = request.queryParams("author");
					String newTitle = request.queryParams("title");
					if (newAuthor != null) {
						book.setAuthor(newAuthor);
					}
					if (newTitle != null) {
						book.setTitle(newTitle);
					}
					return "Book with id '" + id + "' updated";
				} else {
					response.status(404); // 404 Not found
					return "Book not found";
				}
			}
		});

		// Deletes the book resource for the provided id
		delete(new Route("/books/:id") {
			@Override
			public Object handle(Request request, Response response) {
				String id = request.params(":id");
				Book book = books.remove(id);
				if (book != null) {
					return "Book with id '" + id + "' deleted";
				} else {
					response.status(404); // 404 Not found
					return "Book not found";
				}
			}
		});

		// Gets all available book resources (id's)
		get(new Route("/books") {
			@Override
			public Object handle(Request request, Response response) {
				String ids = "";
				for (String id : books.keySet()) {
					ids += id + " ";
				}
				return ids;
			}
		});

	}

}
